import React,{useState,useMemo} from 'react'

const MemoDemo = ({num}) => {
    const [val,setVal] = useState('');
    const [sum,setSum] = useState(0);
    const cal = ()=>{
        let s= 0;
        for(let i=0;i<=val;i++){
            s+=i;
            setSum(s);
        }
    }
const count = useMemo(()=>{
    let s2 =0;
    for(let i=0;i<=num;i++){
        s2+=i;
    }
    return s2;
},[num])//若没有用useMemo包裹，count是个函数，div中调用时需用count（）；
    // 用useMemo包裹后，count是个值，div调用时用count即可
    
    return (
        <div>
            <input type="text" onChange={e=>setVal(e.target.value)}/>
            <button onClick={cal}>计算</button>
            <div>当前组件计算结果-----{sum}</div>
            <div>父组件计算结果-----{count}</div>
        </div>
    )
}

export default MemoDemo

